import os
import subprocess
from xhs.my_log import log
# 本地已通过USB连接的设备
def get_usb_devices():
    output = subprocess.check_output("adb devices", shell=True).decode()
    return [line.split('\t')[0] for line in output.splitlines() if '\tdevice' in line and not ':' in line]

# 获取设备IP
def get_device_ip(device_id):
    try:
        output = subprocess.check_output(f'adb -s {device_id} shell ip addr show wlan0', shell=True).decode()
        for line in output.splitlines():
            line = line.strip()
            if line.startswith("inet "):
                return line.split(" ")[1].split("/")[0]
    except:
        return None

# 批量切换并连接
def connect_all_devices():
    devices = get_usb_devices()
    for device in devices:
        log(f"=======================================================================开始处理设备: {device}")

        # 先获取 IP，再切换 tcpip 模式
        ip = get_device_ip(device)
        if not ip:
            log(f"获取IP失败: {device}")
            continue

        log(f"{device} 的 IP 是: {ip}")
        subprocess.call(f'adb -s {device} tcpip 5555', shell=True)

        # 等待1秒让设备切换完成
        import time
        time.sleep(1)

        # 使用 IP 连接
        result = subprocess.call(f'adb connect {ip}:5555', shell=True)
        if result == 0:
            log(f"连接成功: {ip}")
        else:
            log(f"连接失败: {ip}")
